package com.finance.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finance.entity.CardIssue;
import com.finance.mapper.CardIssueMapper;
import com.finance.service.CardIssueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * C03
 * 发卡数据Service实现类
 */
@Slf4j
@Service
public class CardIssueServiceImpl extends ServiceImpl<CardIssueMapper, CardIssue> implements CardIssueService {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate) {
        return processOrders(records, searchDate, forceUpdate, null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate, String cinemaId) {
        if (records == null || records.isEmpty()) {
            return 0;
        }

        // 如果不是强制更新，先检查数据是否存在
        if (!forceUpdate) {
            long count = lambdaQuery()
                    .eq(CardIssue::getSearchDate, searchDate)
                    .eq(CardIssue::getCinemaId, cinemaId)
                    .count();
            if (count > 0) {
                log.info("C03数据已存在，searchDate: {}, cinemaId: {}, 跳过处理", searchDate, cinemaId);
                return 0;
            }
        } else {
            // 如果是强制更新，先删除指定日期的数据
            lambdaUpdate()
                    .eq(CardIssue::getSearchDate, searchDate)
                    .eq(CardIssue::getCinemaId, cinemaId)
                    .remove();
        }

        List<CardIssue> orderList = new ArrayList<>();
        for (Map<String, String> record : records) {
            try {
                CardIssue order = new CardIssue();

                // 设置影院ID
                order.setCinemaId(cinemaId);
                //发卡时间,开卡时间,发卡影院名称,订单号,卡号,卡类型,卡政策,卡政策编码,是否实体卡,应收工本费
                // 处理日期时间字段
                String issueTimeStr = record.get("发卡时间");
                if (StringUtils.hasText(issueTimeStr)) {
                    order.setIssueTime(LocalDateTime.parse(issueTimeStr, DATE_TIME_FORMATTER));
                }

                String activateTimeStr = record.get("开卡时间");
                if (StringUtils.hasText(activateTimeStr)) {
                    order.setActivateTime(LocalDateTime.parse(activateTimeStr, DATE_TIME_FORMATTER));
                }

                // 处理字符串字段
                if (StringUtils.hasText(record.get("发卡影院名称"))) {
                    order.setIssueCinemaName(record.get("发卡影院名称"));
                }
                if (StringUtils.hasText(record.get("订单号"))) {
                    order.setOrderNo(record.get("订单号"));
                }
                if (StringUtils.hasText(record.get("卡号"))) {
                    order.setCardNo(record.get("卡号"));
                }
                if (StringUtils.hasText(record.get("卡类型"))) {
                    order.setCardType(record.get("卡类型"));
                }
                if (StringUtils.hasText(record.get("卡政策"))) {
                    order.setCardPolicy(record.get("卡政策"));
                }
                if (StringUtils.hasText(record.get("卡政策编码"))) {
                    order.setCardPolicyCode(record.get("卡政策编码"));
                }
                if (StringUtils.hasText(record.get("是否实体卡"))) {
                    order.setIsPhysicalCard(record.get("是否实体卡"));
                }
                // 处理数字字段
                String cardFeeStr = record.get("应收工本费");
                if (StringUtils.hasText(cardFeeStr)) {
                    order.setCardFee(Long.parseLong(cardFeeStr));
                }
                // 实收工本费,开卡金额,会费,支付工具,支付工具编码,销售方式,发卡渠道,发卡渠道编码
                String actualCardFeeStr = record.get("实收工本费");
                if (StringUtils.hasText(actualCardFeeStr)) {
                    order.setActualCardFee(Long.parseLong(actualCardFeeStr));
                }
                String activateAmountStr = record.get("开卡金额");
                if (StringUtils.hasText(activateAmountStr)) {
                    order.setActivateAmount(Long.parseLong(activateAmountStr));
                }
                String membershipFeeStr = record.get("会费");
                if (StringUtils.hasText(membershipFeeStr)) {
                    order.setMembershipFee(Long.parseLong(membershipFeeStr));
                }
                // 处理字符串字段
                if (StringUtils.hasText(record.get("支付工具"))) {
                    order.setPayTool(record.get("支付工具"));
                }
                if (StringUtils.hasText(record.get("支付工具编码"))) {
                    order.setPayToolCode(record.get("支付工具编码"));
                }
                if (StringUtils.hasText(record.get("销售方式"))) {
                    order.setSaleType(record.get("销售方式"));
                }
                if (StringUtils.hasText(record.get("发卡渠道"))) {
                    order.setIssueChannel(record.get("发卡渠道"));
                }
                if (StringUtils.hasText(record.get("发卡渠道编码"))) {
                    order.setIssueChannelCode(record.get("发卡渠道编码"));
                }
                // 操作员工号,操作员,工作站名称,卡数量,是否开卡充值,开卡充值金额,影院国家编码,影院所属区域
                if (StringUtils.hasText(record.get("操作员工号"))) {
                    order.setOperatorEmployeeNo(record.get("操作员工号"));
                }
                if (StringUtils.hasText(record.get("操作员"))) {
                    order.setOperator(record.get("操作员"));
                }
                if (StringUtils.hasText(record.get("工作站名称"))) {
                    order.setWorkstationName(record.get("工作站名称"));
                }
                // 处理数字字段
                String cardQuantityStr = record.get("卡数量");
                if (StringUtils.hasText(cardQuantityStr)) {
                    order.setCardQuantity(Integer.parseInt(cardQuantityStr));
                }
                if (StringUtils.hasText(record.get("是否开卡充值"))) {
                    order.setIsActivateRecharge(record.get("是否开卡充值"));
                }
                String activateRechargeAmountStr = record.get("开卡充值金额");
                if (StringUtils.hasText(activateRechargeAmountStr)) {
                    order.setActivateRechargeAmount(Long.parseLong(activateRechargeAmountStr));
                }
                // 处理字符串字段
                if (StringUtils.hasText(record.get("影院国家编码"))) {
                    order.setIssueCinemaCode(record.get("影院国家编码"));
                }
                if (StringUtils.hasText(record.get("影院所属区域"))) {
                    order.setCinemaArea(record.get("影院所属区域"));
                }
                // 影城所属区域编码,会员ID,商户订单号,第三方支付流水号
                if (StringUtils.hasText(record.get("影城所属区域编码"))) {
                    order.setCinemaAreaCode(record.get("影城所属区域编码"));
                }
                if (StringUtils.hasText(record.get("会员ID"))) {
                    order.setMemberId(record.get("会员ID"));
                }
                if (StringUtils.hasText(record.get("商户订单号"))) {
                    order.setMerchantOrderNo(record.get("商户订单号"));
                }
                if (StringUtils.hasText(record.get("第三方支付流水号"))) {
                    order.setThirdPartyPayNo(record.get("第三方支付流水号"));
                }
                // 设置searchDate
                order.setSearchDate(searchDate);

                // 处理会员卡有效期
                if (StringUtils.hasText(record.get("会员卡有效期"))) {
                    order.setCardValidityPeriod(record.get("会员卡有效期"));
                }

                orderList.add(order);
            } catch (Exception e) {
                log.error("处理发卡记录失败: {}", record, e);
            }
        }

        try {
            if (!orderList.isEmpty()) {
                return saveBatch(orderList) ? orderList.size() : 0;
            }
            return 0;
        } catch (Exception e) {
            log.error("批量保存发卡数据失败", e);
            throw e;
        }
    }
} 